package com.biz.solr.biz.conifg;

import com.biz.solr.entity.IDoc;
import com.biz.solr.exceptions.BizSolrConfigException;
import com.biz.solr.exceptions.BizSolrInitException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;

/**
 * @ClasName BIZConfigHelper
 * @Descripution TODO
 * @Author USER
 * @Date 2022/3/26 9:12
 * @Version V1.0
 */
@Component
public class BIZConfigHelper {

    @Value("${biz.search.config}")
    private String configClass;

    //根据当前业务 去初始化对就实体的对应关系
    public void InitBIZConfig() {
        try {
            LoadByConfigClass();
            BIZConfig[] bizs = BIZConfig.values();
            for (BIZConfig biz : bizs) {
                Object docClass = biz.getDocClass();

                HashMap<String,String> filedRules =new HashMap<>();
                java.lang.reflect.Field[] fields = docClass.getClass().getDeclaredFields();
                for (java.lang.reflect.Field field : fields) {
                    String kv = field.getName();
                    if(! kv.equals("serialVersionUID"))
                        filedRules.put(kv,kv);
                }
                ((IDoc) docClass).setRelevanceField(filedRules);
                ((IDoc) docClass).afterAddBizTypeRelevanceField();
            }
        } catch (BizSolrConfigException e) {
          throw new BizSolrInitException("初始化错误");
        }catch (Exception e){
            throw new BizSolrInitException("初始化错误");
        }
    }

    private void LoadByConfigClass() throws Exception,BizSolrConfigException{
        try {
            Class<?> aClass = Class.forName(configClass);
            Object[] enumConstants = aClass.getEnumConstants();
            Method getBizCore = aClass.getMethod("getBizCore");
            Method getBizType = aClass.getMethod("getBizType");
            Method getDocClass = aClass.getMethod("getDocClass");
            for(Object obj: enumConstants){
                String type = (String) getBizType.invoke(obj);
                String core = (String) getBizCore.invoke(obj);
                Class docClass = (Class) getDocClass.invoke(obj);
                BIZConfig.addConfig(new BIZConfig(type,core,docClass));
            }
        } catch (ClassNotFoundException | NoSuchMethodException e) {
            throw new BizSolrConfigException("配置信息错误！");
        } catch (InvocationTargetException e) {
            throw new BizSolrConfigException("配置信息错误！");
        } catch (IllegalAccessException e) {
            throw new BizSolrConfigException("配置信息错误！");
        }
    }

}
